package com.yeskery.nut.extend.mcp.server.method;

import com.yeskery.nut.bean.ApplicationContext;
import com.yeskery.nut.extend.mcp.core.Constants;
import com.yeskery.nut.extend.mcp.core.JsonMessage;
import com.yeskery.nut.extend.mcp.core.JsonRequest;
import com.yeskery.nut.extend.mcp.core.JsonResponse;
import com.yeskery.nut.extend.mcp.server.*;
import com.yeskery.nut.extend.responsive.JsonResponsive;
import com.yeskery.nut.extend.responsive.ResponsiveConvert;
import com.yeskery.nut.http.SseEmitter;
import com.yeskery.nut.util.JsonNullRemover;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 基础服务方法处理器
 * @author sprout
 * 2025-04-18 14:22
 */
public abstract class BaseServerMethodHandler implements MethodHandler, ResponsiveConvertExpanded {

    /** 日志对象 */
    private static final Logger logger = Logger.getLogger(BaseServerMethodHandler.class.getName());

    /** 应用上下文 */
    private final ApplicationContext applicationContext;

    /** 服务能力 */
    private final McpServerCapability mcpServerCapability;

    /** JSON响应转换器 */
    private volatile ResponsiveConvert responsiveConvert;

    /**
     * 构造基础服务方法处理器
     * @param applicationContext 应用上下文
     * @param mcpServerCapability 服务能力
     */
    protected BaseServerMethodHandler(ApplicationContext applicationContext, McpServerCapability mcpServerCapability) {
        this.applicationContext = applicationContext;
        this.mcpServerCapability = mcpServerCapability;
    }

    @Override
    public JsonResponse handle(McpServerSession serverSession, JsonMessage jsonMessage) throws McpException {
        boolean requestMessage = isJsonRequestMessage();
        JsonResponse jsonResponse = requestMessage ? createNewJsonResponse(jsonMessage) : null;
        handleJsonResponse(serverSession, jsonMessage, jsonResponse);
        return requestMessage ? jsonResponse : null;
    }

    /**
     * 处理响应对象
     * @param serverSession 服务端会话
     * @param jsonMessage 请求对象
     * @param jsonResponse 响应对象
     */
    protected abstract void handleJsonResponse(McpServerSession serverSession, JsonMessage jsonMessage, JsonResponse jsonResponse);

    /**
     * 是否为JSON请求消息
     * @return 是否为JSON请求消息
     */
    protected boolean isJsonRequestMessage() {
        return true;
    }

    /**
     * 创建响应对象
     * @param jsonMessage 请求对象
     * @return 响应对象
     */
    protected JsonResponse createNewJsonResponse(JsonMessage jsonMessage) {
        JsonRequest jsonRequest = (JsonRequest) jsonMessage;
        JsonResponse jsonResponse = new JsonResponse();
        jsonResponse.setJsonrpc(Constants.JSONRPC);
        jsonResponse.setId(jsonRequest.getId());
        return jsonResponse;
    }

    /**
     * 发送响应消息
     * @param serverSession 服务端会话
     * @param jsonResponse 响应对象
     */
    protected void sendResponseMessage(McpServerSession serverSession, JsonResponse jsonResponse) {
        String responseMessage = JsonNullRemover.removeNullFields(getResponsiveConvert().convertTo(jsonResponse));
        if (logger.isLoggable(Level.FINE)) {
            logger.log(Level.FINE, "MCP Response Body: " + responseMessage);
        }
        serverSession.getSseEmitter().send(SseEmitter.event().name(Constants.MESSAGE_EVENT_TYPE).data(responseMessage));
    }

    /**
     * 获取应用上下文
     * @return 应用上下文
     */
    protected ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 获取服务能力
     * @return 服务能力
     */
    protected McpServerCapability getMcpServerCapability() {
        return mcpServerCapability;
    }

    /**
     * 获取JSON响应转换器
     * @return JSON响应转换器
     */
    protected ResponsiveConvert getResponsiveConvert() {
        if (responsiveConvert == null) {
            synchronized (this) {
                if (responsiveConvert == null) {
                    responsiveConvert = getApplicationContext().getBean(JsonResponsive.class).getResponsiveConvert();
                }
            }
        }
        return responsiveConvert;
    }

    /**
     * 从 {@link java.lang.Object} 转换成 {@link T} 类型
     * @param data {@link java.lang.String} 对象
     * @param clazz 类对象
     * @param <T> {@link T} 类型
     * @return {@link T} 对象
     */
    protected  <T> T converFromObject(Object data, Class<T> clazz) {
        ResponsiveConvert responsiveConvert = getResponsiveConvert();
        return responsiveConvert.convertFromString(JsonNullRemover.removeNullOrEmptyFields(responsiveConvert.convertTo(data)), clazz);
    }

    /**
     * 从 {@link JsonMessage} 转换成 {@link T} 类型
     * @param jsonMessage {@link JsonMessage} 对象
     * @param clazz 类对象
     * @param <T> {@link T} 类型
     * @return {@link T} 对象
     */
    protected <T> T getJsonRequestObject(JsonMessage jsonMessage, Class<T> clazz) {
        JsonRequest jsonRequest = (JsonRequest) jsonMessage;
        return converFromObject(jsonRequest.getParams(), clazz);
    }
}
